package com.hos.punchtheclocksystem.controller;

import com.hos.punchtheclocksystem.framework.Result;
import com.hos.punchtheclocksystem.framework.ResultBean;
import com.hos.punchtheclocksystem.framework.ResultUtil;
import com.hos.punchtheclocksystem.pojo.DoctorAccount;
import com.hos.punchtheclocksystem.pojo.PostCard;
import com.hos.punchtheclocksystem.service.PostCardService;
import com.hos.punchtheclocksystem.service.impl.InfoServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/card")
public class PostCardController {
    @Autowired
    PostCardService postCardService;

    @Autowired
    InfoServiceImpl infoService;

    @PostMapping("/save")
    public Result<String> modify(@RequestBody PostCard entity,HttpServletRequest request) {

        DoctorAccount loginUser = (DoctorAccount) request.getSession().getAttribute("loginUser");
        String docname = infoService.getDoctorInfoByDocId(loginUser.getDoc_id()).getDocname();
        entity.setDoctorname(docname);


        if(entity.getCardid()!=null){
            postCardService.modify(entity);
        }else{
            postCardService.add(entity);
        }
        return ResultUtil.ok();
    }
    @PostMapping("/remove")
    public Result<String> remove(@RequestBody Integer[] ids) {
        postCardService.removes(ids);
        return ResultUtil.ok();
    }

    @GetMapping("/list")
    public ResultBean<List<PostCard>> getPageResult(
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String type,
            @RequestParam(required = false) String doctorname,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer limit,
            HttpServletRequest request) {

        Map<String, Object> param = new HashMap<>(16);

        // 计算起始行号
        int offset = (page - 1) * limit;
        int rows = limit;


        DoctorAccount loginUser = (DoctorAccount) request.getSession().getAttribute("loginUser");

        doctorname = String.valueOf(infoService.getDoctorInfoByDocId(loginUser.getDoc_id()).getDocname());

        param.put("name",name);
        param.put("type",type);
        param.put("doctorname",doctorname);
        param.put("offset", offset);
        param.put("rows", rows);

        // 统计记录数
        int totalRows = postCardService.count(param);

        // 获取当前页结果集
        List<PostCard> entities = postCardService.getPageResult(param);

        return new ResultBean<>(0, "查询成功", totalRows, entities);

    }
}
